package com.xianbeiying.app.ckgl.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.xianbeiying.app.ckgl.MyApplication;
import com.xianbeiying.app.ckgl.R;
import com.xianbeiying.app.ckgl.adapter.EdUpContentdapter;
import com.xianbeiying.app.ckgl.adapter.EdUpTypeadapter;
import com.xianbeiying.app.ckgl.bean.AddressBean;
import com.xianbeiying.app.ckgl.bean.CropsBean;
import com.xianbeiying.app.ckgl.bean.DevicesBean;
import com.xianbeiying.app.ckgl.bean.EdUpBean;
import com.xianbeiying.app.ckgl.bean.GhListBean;
import com.xianbeiying.app.ckgl.bean.UrlBean;
import com.xianbeiying.app.ckgl.http.HttpCallBackUtil;
import com.xianbeiying.app.ckgl.model.GetModel;
import com.xianbeiying.app.ckgl.model.SetModel;
import com.xianbeiying.app.ckgl.util.DataUtil;
import com.xianbeiying.app.ckgl.util.LogUtils;
import com.xianbeiying.app.ckgl.util.ToastUtil;
import com.xianbeiying.app.ckgl.widght.datepop.NumberPickerView;
import com.xianbeiying.app.ckgl.widght.datetimepicker.date.DatePickerDialog;
import com.xianbeiying.app.ckgl.widght.popwindow.CenterPopWindow;
import com.xianbeiying.app.ckgl.widght.popwindow.LayoutPopWindow;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * 编辑更新种类设置
 */
public class EdUpGhActivity extends BaseActivity implements View.OnClickListener, HttpCallBackUtil,DatePickerDialog.OnDateSetListener
{
    private ImageView iv_title_left;
    private TextView tv_title;
    private TextView tv_right_title;
    //温室种类
    private TextView tv_ws;
    //所在地区
    private TextView tv_city;
    //大棚地点
    private EditText tv_address;
    //大棚名称
    private TextView tv_dp_name;
    //大棚面积
    private EditText et_dpmj;
    //预产量
    private EditText et_ycl;
    //实际产量
    private EditText et_sjcl;
    //经度
    private TextView et_jd;
    //纬度
    private TextView et_wd;
    //种植阶段
    private TextView et_zzjd;
    //种植类型
    private TextView et_zzlx;
    //种植产品
    private TextView et_zzcp;
    //种植日期
    private TextView et_zzrq;
    //种植时长
    private EditText et_zzsc;
    //种植面积
    private EditText et_zzmj;
    //氮
    private EditText et_dan;
    //磷
    private EditText et_lin;
    //钾
    private EditText et_jia;
    private GetModel getModel;
    //选择的大棚类型
    private int setSelectPlantDpType;
    //选择种植类型
    private int selectPlantType;
    //选择的种植产品
    private  int selectPlantContent;
    //大棚名称
    private EditText et_dpmc;
    private GhListBean ghListBean;
    //大棚种类
    private String []  dpType={"塑料温室","日光温室","连栋温室"};
    //种植阶段
    private String [] plantTypess={"育苗","种植"};
    //种植类型阶段的id
    private int selectTypeId;
    private SetModel setModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_gh);
        initView();
    }

    private void initView() {
        getModel = new GetModel(this);
        getModel.addResponseListener(this);

        setModel = new SetModel(this);
        setModel.addResponseListener(this);
        ghListBean = (GhListBean) getIntent().getSerializableExtra("ghListBean");
        iv_title_left = (ImageView) findViewById(R.id.iv_title_left);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_right_title = (TextView) findViewById(R.id.tv_right_title);
        tv_ws = (TextView) findViewById(R.id.tv_ws);
        tv_city = (TextView) findViewById(R.id.tv_city);
        tv_address = (EditText) findViewById(R.id.tv_address);
        tv_dp_name = (TextView) findViewById(R.id.tv_dp_name);
        et_dpmc=(EditText) findViewById(R.id.et_dpmc);
        et_dpmj = (EditText) findViewById(R.id.et_dpmj);
        et_ycl = (EditText) findViewById(R.id.et_ycl);
        et_jd = (TextView) findViewById(R.id.et_jd);
        et_wd = (TextView) findViewById(R.id.et_wd);
        et_zzjd = (TextView) findViewById(R.id.et_zzjd);
        et_zzlx = (TextView) findViewById(R.id.et_zzlx);
        et_zzcp = (TextView) findViewById(R.id.et_zzcp);
        et_zzrq = (TextView) findViewById(R.id.et_zzrq);
        et_zzsc = (EditText) findViewById(R.id.et_zzsc);
        et_zzmj = (EditText) findViewById(R.id.et_zzmj);
        et_dan = (EditText) findViewById(R.id.et_dan);
        et_lin = (EditText) findViewById(R.id.et_lin);
        et_jia = (EditText) findViewById(R.id.et_jia);
        et_sjcl=(EditText)findViewById(R.id.et_sjcl);
        initData();
        initEvent();
    }
    private List<String> year, month;
    private int yearId, monthId;
    private void initData() {
        year = com.xianbeiying.app.ckgl.util.DataUtil.getTimeHHs();
        yearId = com.xianbeiying.app.ckgl.util.DataUtil.timeHHid;
        month = com.xianbeiying.app.ckgl.util.DataUtil.getTimeMMs();
        monthId = com.xianbeiying.app.ckgl.util.DataUtil.timeMMid;
        tv_title.setText("温室设置");
        tv_right_title.setText("完成");
        setSelectPlantDpType=ghListBean.getV().getGREENHOUSE().getHouseType();
        selectTypeId=ghListBean.getV().getGREENHOUSE().getGrowType();
        tv_ws.setText(dpType[setSelectPlantDpType]);
        et_zzjd.setText(plantTypess[selectTypeId]);
        et_dpmj.setText(ghListBean.getV().getGREENHOUSE().getHouseArea() + "");
        et_dpmc.setText(ghListBean.getV().getGREENHOUSE().getHouseName());
        tv_address.setText(ghListBean.getV().getGREENHOUSE().getHouseAddOther());
        et_jd.setText(ghListBean.getV().getGREENHOUSE().getHouseX() + "");
        et_wd.setText(ghListBean.getV().getGREENHOUSE().getHouseY() + "");
        et_dan.setText(ghListBean.getV().getGREENHOUSE().getSoilK() + "");
        et_lin.setText(ghListBean.getV().getGREENHOUSE().getSoilN() + "");
        et_jia.setText(ghListBean.getV().getGREENHOUSE().getSoilP() + "");
        et_ycl.setText(ghListBean.getV().getGREENHOUSE().getPlantDuration()+"");
        et_sjcl.setText(ghListBean.getV().getGREENHOUSE().getPlantYield()+"");
        et_zzcp.setText(ghListBean.getV().getGREENHOUSE().getCrop().getCropName());
        et_zzmj.setText(ghListBean.getV().getGREENHOUSE().getPlantArea() + "");
        et_zzrq.setText(DataUtil.paserTime(ghListBean.getV().getGREENHOUSE().getPlantTime() + "", "yyyy-MM-dd HH:mm"));
        if (MyApplication.cropsBean != null) {
            cropsBean = MyApplication.cropsBean;
            showPlantTxt();
        } else {
            getModel.GETALLCrops("GET_CROPS", true);
        }
        if (MyApplication.addressBean != null) {
            addressBean = MyApplication.addressBean;
            getAddress();
        } else {
            getModel.GETProvice("GET_ALL_ADDRESS", true);
        }
    }

    private void initEvent(){
        iv_title_left.setOnClickListener(this);
        tv_right_title.setOnClickListener(this);
        tv_ws.setOnClickListener(this);
        tv_city.setOnClickListener(this);
        tv_address.setOnClickListener(this);
        tv_dp_name.setOnClickListener(this);
        et_zzrq.setOnClickListener(this);
        et_zzjd.setOnClickListener(this);
        et_zzlx.setOnClickListener(this);
        et_zzcp.setOnClickListener(this);
        et_zzjd.setOnClickListener(this);

    }
    private CenterPopWindow selectTimes;
    private NumberPickerView mPickerViewH;
    private NumberPickerView mPickerViewM;
    /**
     * GREENHOUSEID：大棚ID
     * HOUSENAME：大棚名称
     * CROPID：农作物ID
     * CROPTYPE：农作物类型
     * GROWTYPE：种植类型
     * HOUSEADD_PRO：省ID
     * HOUSEADD_CITY：市ID
     * HOUSEADD_DIST：区ID
     * HOUSEADD_OTHER：其他地址（String）
     * HOUSEAREA：大棚面积
     * HOUSETYPE：大棚类型
     * HOUSETYPENAME：大棚类型名称
     * HOUSEX：经度
     * HOUSEY：纬度
     * PLANTDURATION：预产量
     * PLANTTIME：种植时间
     * PLANTAREA：种植面积
     * PRODUCTION：实际产量
     * SOILK：钾
     * SOILN：氮
     * SOILP：磷
     */
    @Override
    public void onClick(View v) { //
        switch (v.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            //完成或者编辑
            case R.id.tv_right_title:
//                String tyep=tv_right_title.getText().toString().trim();
//                if(tyep.equals("完成")){
//                }
//                if(tyep.equals("编辑")){
//                    tv_right_title.setText("完成");
//                }
                int gREENHOUSEID=getIntent().getIntExtra("ghId",1);
                String hOUSENAME=et_dpmc.getText().toString().trim()+"";
                String cROPID=cropsBean.getV().getALLCROPS().get(selectPlantType).getCrops().get(selectPlantContent).getCropId()+"";
                String cROPTYPE=cropsBean.getV().getALLCROPS().get(selectPlantType).getCrops().get(selectPlantContent).getCropType()+"";
                String gROWTYPE=selectTypeId+"";
                String hOUSEADD_PRO=ghListBean.getV().getGREENHOUSE().getHouseAddPro()+"";
                String hOUSEADD_CITY=ghListBean.getV().getGREENHOUSE().getHouseAddCity()+"";
                String hOUSEADD_DIST=ghListBean.getV().getGREENHOUSE().getHouseAddDist()+"";
                String hOUSEADD_OTHER=tv_address.getText().toString().trim();
                String hOUSEAREA=et_dpmj.getText().toString().trim();
                String hOUSETYPE=setSelectPlantDpType+"";
                String hOUSETYPENAME=dpType[setSelectPlantDpType];
                String hOUSEX=ghListBean.getV().getGREENHOUSE().getHouseX()+"";
                String hOUSEY=ghListBean.getV().getGREENHOUSE().getHouseY()+"";
                String pLANTDURATION=et_ycl.getText().toString().trim();
                String pLANTTIME=et_zzrq.getText().toString().trim();
                String pLANTAREA=et_zzmj.getText().toString().trim();
                String  pRODUCTION=et_sjcl.getText().toString().trim();
//                String sOILK=ghListBean.getV().getGREENHOUSE().getSoilK()+"";
//                String sOILN=ghListBean.getV().getGREENHOUSE().getSoilN()+"";
//                String sOILP=ghListBean.getV().getGREENHOUSE().getSoilP()+"";
                String sOILK=et_dan.getText().toString().trim();
                String sOILN=et_lin.getText().toString().trim();
                String sOILP=et_jia.getText().toString().trim();
                LogUtils.e("时间========",pLANTTIME);
                setModel.UPDATE_GREENHOUSE("UPDATE_GREENHOUSE",gREENHOUSEID,hOUSENAME,cROPID,cROPTYPE,gROWTYPE,hOUSEADD_PRO,hOUSEADD_CITY,
                        hOUSEADD_DIST,hOUSEADD_OTHER,hOUSEAREA,hOUSETYPE,hOUSETYPENAME,hOUSEX,hOUSEY,pLANTDURATION,pLANTTIME,pLANTAREA,
                        pRODUCTION,sOILK,sOILN,sOILP,true);
                break;
            //温室种类
            case R.id.tv_ws:
                popWindowPlanDptype();
                break;
            //所在地区
            case R.id.tv_city:
                break;
            //大棚地点
            case R.id.tv_address:
                break;
            //大棚名称
            case R.id.tv_dp_name:
                break;
            //种植日期
            case R.id.et_zzrq:
                showTimePopWindow();
                break;
            //种植类型
            case R.id.et_zzlx:
                popWindowPlantType();
                break;
            //种植阶段
            case R.id.et_zzjd:
                popWindowPlanTypess();
                break;
            //种植产品
            case R.id.et_zzcp:
                popWindowPlantProject();
                break;
            //确定
            case R.id.tv_pop_qtime:
                String yearss = et_year.getText().toString();
                String months = et_month.getText().toString();
                String days = et_day.getText().toString();
                String hhs = et_hh.getText().toString();
                String mms = et_mm.getText().toString();
                if (yearss.isEmpty()){
                    ToastUtil.showInfo(EdUpGhActivity.this, "请选择年份");
                    return;
                }
                if (months.isEmpty()) {
                    ToastUtil.showInfo(EdUpGhActivity.this, "请选择月份");
                    return;
                }
                if (days.isEmpty()) {
                    ToastUtil.showInfo(EdUpGhActivity.this, "请选择日期");
                    return;
                }
                if (hhs.isEmpty()) {
                    ToastUtil.showInfo(EdUpGhActivity.this, "请选择小时");
                    return;
                }
                if (mms.isEmpty()) {
                    ToastUtil.showInfo(EdUpGhActivity.this, "请选择分钟");
                    return;
                }
                int endTime = com.xianbeiying.app.ckgl.util.DataUtil.getTime(yearss + "-" + months + "-" + days + "  " + hhs + ":" + mms, "yyyy-MM-dd HH:mm");
                int downTime = com.xianbeiying.app.ckgl.util.DataUtil.getTime(com.xianbeiying.app.ckgl.util.DataUtil.dateHTime(), "yyyy-MM-dd HH:mm");
                if (endTime < downTime) {
                    ToastUtil.showInfo(EdUpGhActivity.this, "选择时间不能小于当前时间");
                    return;
                }
                if (selectTime != null && selectTime.isShowing()) {
                    selectTime.dismiss();
                    et_zzrq.setText(yearss + "-" + months + "-" + days + "  " + hhs + ":" + mms);
                }
                break;
            //年
            case R.id.et_year:
                //月
            case R.id.et_month:
                //日
            case R.id.et_day:
                final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(this, calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), true);
                datePickerDialog.setYearRange(1985, 2028);
                datePickerDialog.setCloseOnSingleTapDay(true);
                datePickerDialog.show(getSupportFragmentManager(), "");
                break;
            //时//分
            case R.id.et_hh:
            case R.id.et_mm:
                selectTimes=new CenterPopWindow(EdUpGhActivity.this,R.layout.pop_window_numbertime);
                mPickerViewH =selectTimes.getView(R.id.picker_hour);
                mPickerViewM =selectTimes.getView(R.id.picker_minute);
                initTime();
                selectTimes.setTextOnClickListener(R.id.done,this);
                selectTimes.setTextOnClickListener(R.id.ly_pop_time,this);
                break;
            //时间的确认
            case R.id.ly_pop_time:
                selectTimes.dismiss();
                break;
            case R.id.done:
                et_hh.setText(mPickerViewH.getContentByCurrValue());
                et_mm.setText(mPickerViewM.getContentByCurrValue());
                selectTimes.dismiss();
                break;
        }
    }
    //时间的设置
    private void initTime(){
        GregorianCalendar calendar = (GregorianCalendar) GregorianCalendar.getInstance();
        int h = calendar.get(Calendar.HOUR_OF_DAY);
        int m = calendar.get(Calendar.MINUTE);
        h = h % 24;
        setData(mPickerViewH, 0, 23, h);
        setData(mPickerViewM, 0, 59, m);
    }

    private void setData(NumberPickerView picker, int minValue, int maxValue, int value){
        picker.setMinValue(minValue);
        picker.setMaxValue(maxValue);
        picker.setValue(value);
    }
    private DevicesBean devicesBean;//大棚返回的数据
    private CropsBean cropsBean;
    private AddressBean addressBean;
    private EdUpBean edUpBean;
    private CenterPopWindow selectTime;
    private TextView et_year, et_month, et_day, et_hh, et_mm;

    private  void showTimePopWindow(){
        selectTime = new CenterPopWindow(this, R.layout.pop_choice_time);
        selectTime.setText(R.id.pop_time_title, "选择日期");
        et_year = selectTime.getView(R.id.et_year);
        et_month = selectTime.getView(R.id.et_month);
        et_day = selectTime.getView(R.id.et_day);
        et_hh = selectTime.getView(R.id.et_hh);
        et_mm = selectTime.getView(R.id.et_mm);
        selectTime.setTextOnClickListener(R.id.et_year, this);
        selectTime.setTextOnClickListener(R.id.et_month, this);
        selectTime.setTextOnClickListener(R.id.et_day, this);
        selectTime.setTextOnClickListener(R.id.et_hh, this);
        selectTime.setTextOnClickListener(R.id.et_mm, this);
        //关闭窗口
        selectTime.setTextOnClickListener(R.id.ly_pop_chocice_time, this);
        //确定
        selectTime.setTextOnClickListener(R.id.tv_pop_qtime, this);
    }
    @Override
    public void onCallBackData(String url, Object content) {
        if (url.equals("农作物")){
            if (content != null) {
                cropsBean = JSON.parseObject(new String((byte[]) content), CropsBean.class);
                MyApplication.cropsBean = cropsBean;
                showPlantTxt();
            }
        }
        if (url.equals("所有的省")) {
            if (content != null) {
                addressBean = JSON.parseObject(new String((byte[]) content), AddressBean.class);
                MyApplication.addressBean = addressBean;
                getAddress();
            }
        }
        if(url.equals("更新大棚")){
            edUpBean=JSON.parseObject(new String((byte[]) content), EdUpBean.class);
            if(edUpBean.isR()){
                ToastUtil.showInfo(EdUpGhActivity.this,"更新成功");
                //获取大棚数据
                getModel.QUWEYDEVS(false);
            }else{
                ToastUtil.showInfo(EdUpGhActivity.this,edUpBean.getERR_MSG());
            }
        }

        //大棚数据
        if (url.equals(UrlBean.QUWEYDEVS)) {
            if (content != null) {
                devicesBean = JSON.parseObject(new String((byte[]) content), DevicesBean.class);
                MyApplication.devicesBean = devicesBean;
                finish();
            }
        }
    }

    private void showPlantTxt() {

        int size=cropsBean.getV().getALLCROPS().size();
        for(int i=0;i<size;i++){
            if(cropsBean.getV().getALLCROPS().get(i).getCropType()==ghListBean.getV().getGREENHOUSE().getCrop().getCropType()){
                et_zzlx.setText(cropsBean.getV().getALLCROPS().get(i).getCropTypeName());
            }
        }
    }
    private LayoutPopWindow plantType, plantProject,planDptype,cpPlantType;
    private ListView plantTypeList, plantProjectList,planDptypeList,cpPlantTypeList;
    private EdUpContentdapter cpContentadapter;
    private EdUpTypeadapter cpTypeadapter,cpDpAdapter,cpPlantTypeAdapter;
    /**
     * 种植类型
     */
    private void popWindowPlanTypess() {
        cpPlantType = new LayoutPopWindow(this, R.layout.pop_window_edupgh, et_zzjd);
        cpPlantTypeList = cpPlantType.getView(R.id.pop_edup_lists);
        cpPlantTypeAdapter = new EdUpTypeadapter(this, plantTypess);
        cpPlantTypeList.setAdapter(cpPlantTypeAdapter);
        cpPlantTypeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                cpPlantType.dismiss();
                et_zzjd.setText(plantTypess[position]);
                selectTypeId = position;
            }
        });
    }

    /**
     * 大棚类型
     */
    private void popWindowPlanDptype() {
        planDptype = new LayoutPopWindow(this, R.layout.pop_window_edupgh, tv_ws);
        planDptypeList = planDptype.getView(R.id.pop_edup_lists);
        cpDpAdapter = new EdUpTypeadapter(this, dpType);
        planDptypeList.setAdapter(cpDpAdapter);
        planDptypeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                planDptype.dismiss();
                tv_ws.setText(dpType[position]);
                setSelectPlantDpType = position;
            }
        });
    }
    /**
     * 种植类型
     */
    private void popWindowPlantType() {
        plantType = new LayoutPopWindow(this, R.layout.pop_window_edupgh, et_zzlx);
        plantTypeList = plantType.getView(R.id.pop_edup_lists);
        cpTypeadapter = new EdUpTypeadapter(this, cropsBean);
        plantTypeList.setAdapter(cpTypeadapter);
        plantTypeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                plantType.dismiss();
                et_zzlx.setText(cropsBean.getV().getALLCROPS().get(position).getCropTypeName());
                selectPlantType = position;
            }
        });
    }

    /**
     * 种植产品
     */
    private void popWindowPlantProject(){
        plantProject = new LayoutPopWindow(this, R.layout.pop_window_edupgh, et_zzcp);
        plantProjectList = plantProject.getView(R.id.pop_edup_lists);
        cpContentadapter = new EdUpContentdapter(this, cropsBean.getV().getALLCROPS().get(selectPlantType).getCrops());
        plantProjectList.setAdapter(cpContentadapter);
        plantProjectList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                plantProject.dismiss();
                selectPlantContent=position;
                et_zzcp.setText(cropsBean.getV().getALLCROPS().get(selectPlantType).getCrops().get(position).getCropName());
            }
        });
    }

    //更加id显示出省市区
    private void getAddress() {
        StringBuffer sb = new StringBuffer();
        int proviceSize = addressBean.getV().getADDRESS().size();
        for (int i = 0; i < proviceSize; i++) {
            if (addressBean.getV().getADDRESS().get(i).getProvinceid() == ghListBean.getV().getGREENHOUSE().getHouseAddPro()) {
                sb.append(addressBean.getV().getADDRESS().get(i).getProvincename() + "/");
                int citySize = addressBean.getV().getADDRESS().get(i).getCitys().size();
                for (int j = 0; j < citySize; j++) {
                    if (addressBean.getV().getADDRESS().get(i).getCitys().get(j).getId() == ghListBean.getV().getGREENHOUSE().getHouseAddCity()) {
                        sb.append(addressBean.getV().getADDRESS().get(i).getCitys().get(j).getCityname() + "/");
                        int areaSize = addressBean.getV().getADDRESS().get(i).getCitys().get(j).getDistricts().size();
                        for (int m = 0; m < areaSize; m++) {
                            if (addressBean.getV().getADDRESS().get(i).getCitys().get(j).getDistricts().get(m).getDistrictid() == ghListBean.getV().getGREENHOUSE().getHouseAddDist()) {
                                sb.append(addressBean.getV().getADDRESS().get(i).getCitys().get(j).getDistricts().get(m).getDistrictname());
                            }
                        }
                    }
                }
                tv_city.setText(sb.toString());
            }

        }

    }

    @Override
    public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
        et_year.setText(year + "");
//        if((month+1)<10){
//            et_month.setText("0"+(month + 1) + "");
//        }else{
            et_month.setText((month + 1) + "");
//        }
//        if(day<10){
//            et_day.setText("0"+day + "");
//        }else{
            et_day.setText(day + "");
//        }

    }
}
